#!/usr/bin/env python
# coding: utf-8


import Database
import socket
import json
db = Database.DataBase(file='UNData.xml')
ip_port = (socket.gethostname(), 8080)
sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)            # create a socket
sk.bind(ip_port)                # bind host address and port together
sk.listen(20)                    # # configure how many client the server can listen simultaneously
print('Starting socket，waiting for connection...')
while True:
    conn, address = sk.accept()# # accept new connection
    # receive data stream. it won't accept data packet greater than 1024 bytes
    while True:
        
        try:
            client_data = conn.recv(1024).decode()
        except Exception as e:
            conn.close()
            break
        client_data = str(client_data)
        dataStr = db.qurey_db(client_data)
        print("Message from Client %s：%s" % (address, client_data))
        conn.send(dataStr.encode()) # # send data to the client
sk.close()
